package openmyexplorer.actions;

import java.io.IOException;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;

import openmyexplorer.util.Messages;
import openmyexplorer.util.OperatingSystem;

public class OpenExplorerHandler extends AbstractHandler {
	protected IWorkbenchWindow window;
	protected Shell shell;
	protected ISelection currentSelection;
	protected String systemBrowser;

	public OpenExplorerHandler() {
		this.systemBrowser = OperatingSystem.INSTANCE.getSystemBrowser();
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// 系统路径
		if (OperatingSystem.INSTANCE.isLinux()) {
			this.systemBrowser = OperatingSystem.INSTANCE.getSystemBrowser();
		}
		window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
		StringBuilder sb = new StringBuilder();
		sb.append("-------------------------------------------------------------").append("\n");
		sb.append(formatInfo("systemBrowser")).append(systemBrowser).append("\n");
		this.currentSelection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getSelection();
		if (this.currentSelection instanceof ITreeSelection) {
			sb.append(formatInfo("currentSelection")).append(ITreeSelection.class.getSimpleName()).append("\n");;
		}
		if (this.currentSelection instanceof ITextSelection) {
			sb.append(formatInfo("currentSelection")).append(ITextSelection.class.getSimpleName()).append("\n");;
		}
		if (this.currentSelection instanceof IStructuredSelection) {
			sb.append(formatInfo("currentSelection")).append(IStructuredSelection.class.getSimpleName()).append("\n");
		}
		sb.append("-------------------------------------------------------------").append("\n");
		System.out.println(sb);
		try {
			if ((this.currentSelection == null) || (this.currentSelection.isEmpty())) {
				return null;
			}
			if ((this.currentSelection instanceof ITreeSelection)) {

				ITreeSelection treeSelection = (ITreeSelection) this.currentSelection;

				TreePath[] paths = treeSelection.getPaths();

				for (int i = 0; i < paths.length; i++) {
					TreePath path = paths[i];
					IResource resource = null;
					Object segment = path.getLastSegment();
					if ((segment instanceof IResource))
						resource = (IResource) segment;
					else if ((segment instanceof IJavaElement)) {
						resource = ((IJavaElement) segment).getResource();
					}
					if (resource != null) {
						String browser = this.systemBrowser;
						String location = resource.getLocation().toOSString();
						if ((resource instanceof IFile)) {
							location = ((IFile) resource).getParent().getLocation().toOSString();
							if (OperatingSystem.INSTANCE.isWindows()) {
								browser = this.systemBrowser + " /select,";
								location = ((IFile) resource).getLocation().toOSString();
							}
						}
						openInBrowser(browser, location);
					}
				}
			} else if (((this.currentSelection instanceof ITextSelection))
					|| ((this.currentSelection instanceof IStructuredSelection))) {
				IEditorPart editor = this.window.getActivePage().getActiveEditor();
				if (editor != null) {
					IFile current_editing_file = (IFile) editor.getEditorInput().getAdapter(IFile.class);
					String browser = this.systemBrowser;
					String location = current_editing_file.getParent().getLocation().toOSString();
					if (OperatingSystem.INSTANCE.isWindows()) {
						browser = this.systemBrowser + " /select,";
						location = current_editing_file.getLocation().toOSString();
					}
					openInBrowser(browser, location);
				}
			}
		} catch (Exception e) {
			MessageDialog.openInformation(window.getShell(), "打开资源管理器异常", e.getMessage() + "!!!");
		}
		return null;
	}

	protected void openInBrowser(String browser, String location) {
		try {
			if (OperatingSystem.INSTANCE.isWindows())
				Runtime.getRuntime().exec(browser + " \"" + location + "\"");
			else
				Runtime.getRuntime().exec(new String[] { browser, location });
		} catch (IOException e) {
			MessageDialog.openError(this.shell, Messages.OpenExploer_Error,
					Messages.Cant_Open + " \"" + location + "\"");
			e.printStackTrace();
		}
	}

	public String formatInfo(String str) {
		return String.format("===%s===>", str);
	}
}
